#!/bin/bash

# MySQL MCP Server SSE 模式启动脚本

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "=== MySQL MCP Server SSE 模式启动脚本 ==="

# 设置默认值
MYSQL_HOST=${MYSQL_HOST:-localhost}
MYSQL_PORT=${MYSQL_PORT:-3306}
MYSQL_USER=${MYSQL_USER:-root}
MYSQL_DATABASE=${MYSQL_DATABASE:-test}
SERVER_HOST=${SERVER_HOST:-localhost}
SERVER_PORT=${SERVER_PORT:-8080}

# 检查必需的环境变量
if [ -z "$MYSQL_USER" ]; then
    echo "错误: 请设置 MYSQL_USER 环境变量"
    echo "使用方法: MYSQL_USER=your_user MYSQL_DATABASE=your_db $0"
    exit 1
fi

if [ -z "$MYSQL_DATABASE" ]; then
    echo "错误: 请设置 MYSQL_DATABASE 环境变量"
    echo "使用方法: MYSQL_USER=your_user MYSQL_DATABASE=your_db $0"
    exit 1
fi

# 如果没有设置密码，提示用户输入
if [ -z "$MYSQL_PASSWORD" ]; then
    read -s -p "请输入 MySQL 密码: " MYSQL_PASSWORD
    echo
    export MYSQL_PASSWORD
fi

# 设置服务器模式
export SERVER_MODE=sse
export SERVER_HOST
export SERVER_PORT
export MYSQL_HOST
export MYSQL_PORT
export MYSQL_USER
export MYSQL_DATABASE

echo "配置信息:"
echo "  数据库: $MYSQL_HOST:$MYSQL_PORT/$MYSQL_DATABASE"
echo "  用户: $MYSQL_USER"
echo "  SSE端点: http://$SERVER_HOST:$SERVER_PORT/sse"
echo "  消息端点: http://$SERVER_HOST:$SERVER_PORT/message"
echo

# 构建并启动服务器
if [ ! -f "$PROJECT_ROOT/bin/mysql-mcp-server" ]; then
    echo "构建服务器..."
    cd "$PROJECT_ROOT/src" && go build -o "$PROJECT_ROOT/bin/mysql-mcp-server"
fi

echo "启动 MySQL MCP SSE 服务器..."
echo "按 Ctrl+C 停止服务器"
echo

exec "$PROJECT_ROOT/bin/mysql-mcp-server" 